var express = require('express');
var router = express.Router();
var modules = require("../util/js_load")

var controller = {}

function isPromise(obj) {
  return !!obj  //有实际含义的变量才执行方法，变量null，undefined和''空串都为false
  	&& (typeof obj === 'object' || typeof obj === 'function') // 初始promise 或 promise.then返回的
  	&& typeof obj.then === 'function';
}

modules.init('./js_module/', controller)

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/js_service', function(req, res, next) {
  const path = req.query.path;
  const data = eval(req.query.params);
  const method = req.query.method;
  const result = controller[path][method].apply(this, data);
  if (isPromise(result)) {
    result.then(data=>{
      res.json({status: 200, data});
    })
  } else {
    res.json({status: 200, data: result});
  }
});


router.post('/js_service', function(req, res, next) {
  const body = req.body;
  const path = body.path;
  const data = eval(body.params);
  const method = body.method;
  const result = controller[path][method].apply(this, data);
  if (isPromise(result)) {
    result.then(data=>{
      res.json({status: 200, data});
    })
  } else {
    res.json({status: 200, data: result});
  }
});

// pm2 start npm -- start
module.exports = router;
